// Run.js - 执行测试并生成CSV结果文件

// 获取命令行参数
const args = process.argv.slice(2);
if (args.length !== 1) {
    console.error("请提供一个JS文件作为参数");
    process.exit(1);
}

const testFile = args[0];
const CSV_FILE = `${testFile.replace('.js', '')}.csv`;
const CSV_HEADER = "Case,Old,New,Opt\n";

// 测试数组大小常量，需要与t.js中的保持一致
const ARRAY_TEST_SIZES = [10, 100, 1000];

async function runCommand(command) {
    try {
        console.log(`\n执行命令: ${command}`);
        const parts = command.split(" ");
        const proc = Bun.spawn(parts, {
            stdout: "pipe",
            stderr: "pipe",
            env: process.env,
            cwd: process.cwd(),
        });

        const output = await new Response(proc.stdout).text();
        const error = await new Response(proc.stderr).text();

        if (error) {
            console.error(`命令执行出错: ${error}`);
        }

        console.log("命令输出结果:");
        console.log("----------------------------------------");
        console.log(output);
        console.log("----------------------------------------\n");

        return output;
    } catch (error) {
        console.error(`执行命令失败: ${command}`);
        console.error(error.message);
        return null;
    }
}

function extractTimeData(output) {
    if (!output) return {};

    const results = {};

    // 使用新的格式解析测试结果
    const testResults = output.match(/TEST_RESULT: (.*?) \| TIME: ([\d\.]+)/g);
    if (testResults) {
        testResults.forEach((result) => {
            const [_, testName, time] = result.match(
                /TEST_RESULT: (.*?) \| TIME: ([\d\.]+)/
            );
            results[testName] = parseFloat(time);
        });
    }

    return results;
}

function calculateOptimization(value0, value1) {
    if (!value0 || !value1 === 0) {
        return "N/A";
    }

    const improvement = ((value0 - value1) / value0) * 100;
    return improvement.toFixed(2);
}

async function runTests() {
    console.log("开始执行性能测试...");
    console.log("运行 ark rm...");
    await runCommand(`ark ${testFile} rm`);

    console.log("运行 ark abc...");
    await runCommand(`ark ${testFile} abc`);

    console.log("运行 ark asm --only...");
    process.env.OHOS_PATH = "/home/z30052111/ohos/one";
    const output0 = await runCommand(`ark ${testFile} asm --only`);
    const result0 = extractTimeData(output0);

    process.env.OHOS_PATH = "/home/z30052111/ohos/alone";
    console.log("运行 ark asm --only...");
    const output1 = await runCommand(`ark ${testFile} asm --only`);
    const result1 = extractTimeData(output1);

    const allTestCases = new Set([
        ...Object.keys(result0),
        ...Object.keys(result1),
    ]);

    let csvContent = CSV_HEADER;

    allTestCases.forEach((testCase) => {
        const value0 = result0[testCase] || "";
        const value1 = result1[testCase] || "";
        const optimization = calculateOptimization(value0, value1);

        csvContent += `${testCase},${value0},${value1},${optimization}\n`;
    });

    await Bun.write(CSV_FILE, csvContent);
    console.log(`测试结果已保存到 ${CSV_FILE}`);

    console.log("\n===== CSV内容摘要 =====");
    console.log(csvContent);
}

runTests().catch((error) => {
    console.error("测试执行失败:", error);
});
